<?php
Authenticate::requireTechnic();
if($_SERVER['REQUEST_METHOD']=='POST'){
    $pdo = Db::getPDO();
    $pdo->beginTransaction();
    try {
        $package = Package::instance()->getOne($_POST['packageId']);
        $account = Account::instance()->getOne($_POST['accountId']);
        $ip = IP::instance()->getOne($_POST['ipId']);

        $info = $package['info']."\n".$ip['ip'];

        $dateTimeout = new DateTime();
        $dateTimeout = $dateTimeout->add(new DateInterval('P'.$_POST['month'].'M'));

        Product::instance()->add(array(
            'type'=> 'colo',
            'packageId'=> $_POST['packageId'],
            'month'=> $_POST['month'],
            'accountId'=> $_POST['accountId'],
            'note'=> $_POST['note'],
            'dateTimeout'=> $dateTimeout->format('Y-m-d'),
            'status'=> 1));

        $id = $pdo->lastInsertId();
        ProductColo::instance()->add(array(
            'id'=> $id,
            'ipId'=> $_POST['ipId']));

        $pdo->commit();
        echo json_encode(array('success'=> true));
    }
    catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(array('error'=> array('code'=> $e->getCode(), 'message'=> $e->getMessage())));
    }

    //Notify::setUp($account['email'], 'Colo', $package['name'], $_POST['month'], $date->format('j/n/Y'), nl2br($info));
}
else if($_SERVER['REQUEST_METHOD'] == 'PUT'){
    parse_str(file_get_contents("php://input"), $formData);

    $set = $formData;
    $id = $set['id'];
    unset($set['id']);

    if(!Product::edit($id, $set)){
        throw new Exception('Product::edit failed');
    }

    echo json_encode(array('success'=> true));
    $db->commit();
}